import 'dart:typed_data';
import 'dart:io';
import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';
import 'package:exif/exif.dart';
import 'package:share_plus/share_plus.dart';
import 'package:path/path.dart' as path;

class ImageHelper {
  // Extract metadata from the selected image
  static Future<Map<String, IfdTag>?> extractMetadata(File image) async {
    List<int> bytes = await image.readAsBytes();
    return readExifFromBytes(bytes);
  }

  // Save file to a specified directory
  static Future<void> saveToDirectory(
      File file, String directoryPath, String fileName) async {
    final directory = Directory(directoryPath);
    if (!await directory.exists()) {
      await directory.create(recursive: true);
    }
    final newPath = path.join(directory.path, fileName);
    await file.copy(newPath);
  }

// save the Image Without Metadata
  static Future<File> saveImageWithoutMetadata(File image) async {
    Uint8List bytes = await image.readAsBytes();
    img.Image? imgData = img.decodeImage(bytes);

    if (imgData != null) {
      imgData.exif.clear();
      final tempDir = await getTemporaryDirectory();
      final tempPath = tempDir.path;
  final originalFileName = path.basename(image.path);

  // Construct the temporary file path
  final tempFilePath = path.join(tempPath, originalFileName);

  // Create a File object
  final tempFile = File(tempFilePath);
      if (originalFileName.toLowerCase().endsWith('.png')) {
        await tempFile.writeAsBytes(img.encodePng(imgData));
      } else if (originalFileName.toLowerCase().endsWith('.bmp')) {
        await tempFile.writeAsBytes(img.encodeBmp(imgData));
      } else {
        await tempFile.writeAsBytes(img.encodeJpg(imgData));
      }

      return tempFile;
    } else {
      throw Exception('Error decoding image.');
    }
  }

  // Share the cleaned image
  static Future<void> shareImage(String imagePath) async {
    await Share.shareXFiles([XFile(imagePath)],
        text: 'Shared Image with Removed Metadata');
  }
}
